<?php
// 应用公共文件
/**
 * 尝试创建多级文件夹目录
 * @author Diven(702814242@qq.com)
 * @param string $dir
 * @param number $mode
 * @return boolean
 */
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) {
        return true;
    }

    if (!mkdirs(dirname($dir), $mode)) {
        return false;
    }

    return @mkdir($dir, $mode);
}
/**
 * 时间计算
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

/**
 * 对象返回数组
 */
function object_to_array($data)
{
    return is_array($data) ? $data : json_decode(json_encode($data));
}

/**
 * 根据出生日期计算年龄
 */
function birthday($birthday)
{
    $age = strtotime($birthday);
    if ($age === false) {
        return false;
    }
    list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
    $now = strtotime("now");
    list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
    $age = $y2 - $y1;
    if ((int) ($m2 . $d2) < (int) ($m1 . $d1)) {
        $age -= 1;
    }

    return $age;
}

/**
 * 判断来源是安卓还是ios
 */
function get_device_type()
{
    //全部变成小写字母
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $type = 'other';
    //分别进行判断
    if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
        $type = 'ios';
    }

    if (strpos($agent, 'android')) {
        $type = 'android';
    }

    return $type;
}

/**获取ip地址 */
function get_ip()
{
    if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } else if (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else if (!empty(['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty(['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    return preg_match('/^\d[\d.]+\d$/', $ip) ? $ip : '';
}

/**
 * @Description: curl请求
 * @Author: Yang
 * @param $url
 * @param null $data
 * @param string $method
 * @param array $header
 * @param bool $https
 * @param int $timeout
 * @return mixed
 */
function curl_request($url, $data = null, $method = 'get', $header = array("content-type: application/json"), $https = true, $timeout = 5)
{
    $method = strtoupper($method);
    $ch = curl_init(); //初始化
    curl_setopt($ch, CURLOPT_URL, $url); //访问的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容，但不输出
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
    }
    if ($method != "GET") {
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true); //请求方式为post请求
        }
        if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //请求数据
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
    $result = curl_exec($ch); //执行请求
    curl_close($ch); //关闭curl，释放资源
    return $result;
}

function object_array($array)
{
    if (is_object($array)) {
        $array = (array) $array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function getrange($len = 6)
{
    $chars = '0123456789';
    mt_srand((float) microtime() * 1000000 * getmypid());
    $number = "";
    while (strlen($number) < $len) {
        $number .= substr($chars, (mt_rand() % strlen($chars)), 1);
    }
    return $number;
}


/**
 *  方法名 ：time_slot
 *  作  用 ：时间段（本日，昨日，本周，上周，本月，上月）
 *  @param ：
 *  @return： 返回时间段
 *  @author：
 *  @date  ：2016/7/14
 */
function time_slot()
{
    $time['today']['begin'] = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
    $time['today']['end'] = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
    $time['tomorrow']['begin'] =  mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
    $time['tomorrow']['end'] =  mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
    $time['week']['begin'] = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
    $time['week']['end'] = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
    $time['lastweek']['begin'] = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
    $time['lastweek']['end'] = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
    $time['month']['begin'] = mktime(0, 0, 0, date('m'), 1, date('Y'));
    $time['month']['end'] = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
    $time['lastmonth']['begin'] = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));
    $time['lastmonth']['end'] = mktime(23, 59, 59, date("m"), 0, date("Y"));
    //返回时间段
    return $time;
}


function distance($lat1, $lon1, $lat2, $lon2, $radius = 6378.137)
{
    $rad = floatval(M_PI / 180.0);

    $lat1 = floatval($lat1) * $rad;
    $lon1 = floatval($lon1) * $rad;
    $lat2 = floatval($lat2) * $rad;
    $lon2 = floatval($lon2) * $rad;

    $theta = $lon2 - $lon1;

    $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));

    if ($dist < 0) {
        $dist += M_PI;
    }
    return $dist = $dist * $radius;
}

/* 方法二：获取随机字符串
* @param int $randLength 长度
* @param int $addtime 是否加入当前时间戳
* @param int $includenumber 是否包含数字
* @return string
*/
function rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[mt_rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}

/**
 * description：计算离结束还剩多久时间
 * @param string $date
 * @return string
 */
function timer($time)
{
    $t = $time - time(); //单位"秒"
    $day = intval($t / 86400); //天
    $hour = intval((($t / 86400) - $day) * 24); //小时
    $minute = intval((((($t / 86400) - $day) * 24) - $hour) * 60); //分钟
    $second = intval(((((((($t / 86400) - $day) * 24) - $hour) * 60) - $minute) * 60)); //秒

    $str = '';
    if ($day != 0) {
        $str = $day . '天';
    }

    if ($hour != 0) {
        if (strlen($hour) == 1) {
            $hour = "0" . $hour;
        }
        $str .= $hour . '时';
    }

    if ($minute != 0) {
        if (strlen($minute) == 1) {
            $minute = "0" . $minute;
        }
        $str .= $minute . '分';
    }

    if ($second != 0) {
        if (strlen($second) == 1) {
            $second = "0" . $second;
        }
        $str .= $second . '秒';
    }

    return $str;
}
